const http = require('http')
const {Server} = require('socket.io')

const app = http.createServer()

const AutoKeysToMessage = [
  {keys: ['你好', '您好', "嗨", "Hello"], message: '您好，尊贵的客户，您想咨询些什么问题?'},
  {keys: ['位置', '在哪'], message: '您好，您想咨询那个房子'}
]

const kfids = ['zxy', 'ldh', 'lm']

const IO = new Server(app, {
  path: '/mysocket'
})
const chatRoom = {}

IO.on('connection', socket => {
  console.log('链接服务端成功');
  const {id} = socket.handshake.query
  chatRoom[id] = socket.id

  // 相让服务端发送一个消息，把服务端发送消息这个行为封装成了一个信号(方法)
  socket.on('sendMsg', (info) => {
    console.log('服务端接收到了消息');
    const {fromId, toId, message} = info
    socket.to(chatRoom[toId]).emit('reciveMsg', info)
    // 用户发送了一个字符串，并且是发给客服的信息，我们才判定是否命中关键字进行自动回复
    if(typeof message === 'string' && kfids.includes(toId)) {
      AutoKeysToMessage.map(item => {
        if(item.keys.some(key => message.indexOf(key) !== -1)) {
          const messageObj = {
            fromId: toId,
            toId: fromId,
            message: item.message
          }
          socket.emit('reciveMsg', messageObj)
          socket.to(chatRoom[toId]).emit('reciveMsg', messageObj)
        }
      })
    }
  })
  // 注册心跳检测事件
  socket.on('ping', () => {
    socket.emit('pang')
  })
})


app.listen(3000, () => {
  console.log('服务启动成功了');
})